package system.task.quartz;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.util.StringUtils;
import system.task.ExecutorContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HTTP状态
 */
public class HttpJobParam {

    public int connectTimeout = 5000;
    public int socketTimeout = 30 * 1000;
    public final List<Header> headers = new ArrayList<>();
    public final CookieStore cookieStore = new BasicCookieStore();
    public final List<BasicNameValuePair> param = new ArrayList<>();
    public String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 PANSHI/Job";
    public String output = null;
    public String charset = "UTF-8";

    public static HttpJobParam parse(ExecutorContext context) {
        Map<String, Object> param = context.getParam();
        HttpJobParam httpJobParam = new HttpJobParam();
        for (String n : param.keySet()) {
            Object o = param.get(n);
            String v = o == null ? "" : String.valueOf(o);
            //
            if (n.startsWith("_H_")) {
                httpJobParam.headers.add(new BasicHeader(n.substring(3), v));
            } else if (n.startsWith("_C_")) {
                httpJobParam.cookieStore.addCookie(new BasicClientCookie(n.substring(3), v));
            } else if (n.equals("_S_CONN_TIMEOUT")) {
                httpJobParam.connectTimeout = Integer.valueOf(v);
            } else if (n.equals("_S_READ_TIMEOUT")) {
                httpJobParam.socketTimeout = Integer.valueOf(v);
            } else if (n.equals("_S_OUTPUT")) {
                httpJobParam.output = v;
            } else if (n.equals("_S_CHARSET")) {
                httpJobParam.charset = v;
            } else if ("_S_USER_AGENT".equals(n)) {
                if (StringUtils.hasText(v)) {
                    httpJobParam.userAgent = v;
                }
            } else if (n.startsWith("_S_")) {
                throw new RuntimeException("Unknown param " + n);
            } else {
                httpJobParam.param.add(new BasicNameValuePair(n, v));
            }
        }
        httpJobParam.headers.add(new BasicHeader("User-Agent", httpJobParam.userAgent));
        return httpJobParam;
    }

}
